<template>
  <div class="medical-records">
    <h1 class="page-title">就医记录</h1>

    <el-card class="records-table">
      <el-table :data="records" style="width: 100%" border v-loading="isLoading" element-loading-text="数据加载中...">
        <el-table-column prop="appointmentTime" label="预约日期" width="140" sortable />
        <el-table-column prop="deptName" label="科室" width="120" />
        <el-table-column prop="doctorName" label="医生" width="180" />
        <el-table-column prop="reStatus" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.reStatus)" effect="light">
              {{ row.reStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reScore" label="评分" width="250">
          <template #default="{ row }">
            <el-rate  v-model="row.reScore" disabled :max="10" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              :disabled-void-color="'#EFF2F7'" :score-template="(value) => `${value}分`" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMedicalRecordsByUserId } from '@/api/record.js'

export default {
  name: 'MedicalRecords',
  setup() {
    const records = ref([])
    const isLoading = ref(false)
    const showDetailDialog = ref(false)
    const currentRecord = ref(null)

    // 状态类型映射
    const getStatusType = (status) => {
      switch (status) {
        case '已就诊': return 'success'
        case '待就诊': return 'warning'
        case '已过号': return 'info'
        default: return 'info'
      }
    }

    // 获取用户ID
    const getUserId = () => {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      return userInfo.userId || ''
    }

    // 获取就医记录
    const fetchRecords = async () => {
      try {
        isLoading.value = true
        const res = await getMedicalRecordsByUserId(getUserId())
        if (res.code === 200) {
          records.value = res.data.map(item => ({
            ...item,
            appointmentTime: formatDate(item.appointmentTime)
          }))
        }
      } catch (error) {
        ElMessage.error('数据加载失败: ' + (error.message || '未知错误'))
      } finally {
        isLoading.value = false
      }
    }

    // 日期格式化
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '-')
    }

    // 操作处理
    const handleAction = (record) => {
      if (record.reStatus === '待就诊') {
        cancelRecord(record)
      } else {
        evaluateRecord(record)
      }
    }

    // 取消预约
    const cancelRecord = (record) => {
      ElMessageBox.confirm('确定要取消这次预约吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        record.reStatus = '已取消'
        ElMessage.success('预约已取消')
      }).catch(() => { })
    }

    // 查看详情
    const viewDetail = (record) => {
      currentRecord.value = record
      showDetailDialog.value = true
      ElMessage.info(`详细信息：${JSON.stringify(record, null, 2)}`)
    }

    // 评价记录
    const evaluateRecord = (record) => {
      ElMessageBox.prompt('请输入评价内容', '评价', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        if (value) {
          record.reScore = value
          ElMessage.success('评价提交成功')
        }
      }).catch(() => { })
    }

    onMounted(fetchRecords)

    return {
      records,
      isLoading,
      showDetailDialog,
      currentRecord,
      getStatusType,
      handleAction,
      viewDetail,
      cancelRecord,
      evaluateRecord
    }
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.medical-records {
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 28px;
  margin-bottom: 20px;
  color: #42b983;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.records-table {
  margin-bottom: 30px;
}
</style>